import React, { useEffect, useState } from 'react';
import { Radio, Select, Row, Col } from 'antd';
import request from '@/utils/request';
import { stringify } from 'qs';
import { debounce } from 'lodash';

const RadioTxt = {
    update: '已有规章制度更新',
    new: '新规章制度发布'
};

/**
 * 转换字典为 Select 的 Options
 * @param data
 * @param fields
 * @param setOther 是否要保留其他属性
 * @returns {Array|*}
 */
export const getOptionData = (data, fields, setOther = false) => {
    const { key, label } = fields;
    if (!data) return [];
    return (
        data &&
        // eslint-disable-next-line no-confusing-arrow
        data.map(item =>
            !setOther ? { key: item[key], label: item[label] } : { ...item, key: item[key], label: item[label] }
        )
    );
};

const ReleaseType = ({ value = {}, onChange, companyCode, institutionType = 'personnel', disabled }) => {
    const [radioValue, setRadioValue] = useState(1);
    const [institutionList, setInstitutionList] = useState([]);
    const [defaultValue, setDefaultValue] = useState(undefined);

    const handleSelectOnSelect = selectValue => {
        const { key, label } = selectValue;
        if (onChange) {
            onChange({ ...radioValue, originInstitutionName: label, originInstitutionId: key });
        }
    };

    // Radio onChange
    const radioOnChange = radioChangeValue => {
        const { target } = radioChangeValue;
        const t = {
            releaseTypeName: RadioTxt[target?.value],
            releaseType: target?.value,
            originInstitutionName: undefined,
            originInstitutionId: undefined
        };
        if (onChange) {
            onChange(t);
        }
        setRadioValue(t);
    };

    // 搜索制度
    const handleOnSearch = debounce(autoCompleteValue => {
        if (autoCompleteValue?.trim()?.length <= 0) return;

        request(
            `/api/oa/v1/institutions/origin?${stringify({
                institutionType,
                organizationCode: companyCode,
                keyword: autoCompleteValue
            })}`,
            {
                method: 'GET'
            }
        ).then(response => {
            if (response?.code === 10000) {
                const d = getOptionData(response?.data ?? [], {
                    key: 'id',
                    label: 'institutionName'
                });
                setInstitutionList(d);
            }
        });
    }, 500);

    useEffect(() => {
        if (institutionType) {
            setInstitutionList([]);
            setDefaultValue(undefined);
        }
    }, [institutionType]);

    useEffect(() => {
        if (value?.originInstitutionName) {
            setDefaultValue({ label: value?.originInstitutionName, key: value?.originInstitutionId });
        }
    }, [value]);

    return (
        <>
            <Row gutter={24} type="flex" align="bottom">
                <Col span={10}>
                    <Radio.Group
                        onChange={radioOnChange}
                        value={value?.releaseType}
                        disabled={disabled}
                        style={{ lineHeight: '40px' }}
                    >
                        <Radio value="new">新规章制度发布</Radio>
                        <Radio value="update">已有规章制度更新</Radio>
                    </Radio.Group>
                </Col>
                <Col span={14}>
                    <Select
                        value={defaultValue}
                        disabled={disabled}
                        labelInValue
                        showSearch
                        defaultActiveFirstOption={false}
                        showArrow={false}
                        filterOption={false}
                        onSearch={handleOnSearch}
                        onSelect={handleSelectOnSelect}
                        notFoundContent={null}
                        getPopupContainer={trigger => trigger.parentNode}
                        style={{ display: value?.releaseType !== 'update' ? 'none' : 'block' }}
                        placeholder="请搜索已有制度"
                    >
                        {institutionList.map(v => (
                            <Select.Option key={v.key}>{v.label}</Select.Option>
                        ))}
                    </Select>
                </Col>
            </Row>
        </>
    );
};

export default ReleaseType;
